﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sausage.Web.Code;
using Sausage.Common;
using Sausage.Web.DataModel;
using Sausage.Web.Domain;
using Sausage.Web.Models;

namespace Sausage.Web.Controllers
{
    /// <summary>
    /// 突发事件控制器
    /// </summary>
    public class EmergencyController : Controller
    {
        /// <summary>
        /// 默认动作。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [RequireAuthorization]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 默认动作。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [RequireAuthorization]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Submit()
        {
            return View();
        }

        /// <summary>
        /// 查看突发事件。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult ViewEmergency(Guid emergencyID)
        {
            return View(EmergencyHelper.GetEmergencyByID(emergencyID));
        }

        /// <summary>
        /// 发布突发事件。
        /// </summary>
        /// <returns>执行结果。</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [ValidateInput(false)]
        [PermissionCheckAttribute("EmergencyPoster")]
        public JsonResult Create(EmergencyListRow data)
        {
            EmergencyHelper.CreateEmergency(data);
            return Json(new JsonResultViewModel { success = true, message = "突发事件发布成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 查询突发事件详细。
        /// </summary>
        /// <returns>查询结果。</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Details(Guid emergencyID)
        {
            var entity = EmergencyHelper.GetEmergencyByID(emergencyID);
            if (entity == null)
                return Json(new JsonResultViewModel { success = false, message = "指定编号的突发事件不存在！" },
                            JsonRequestBehavior.AllowGet);

            var data = new
                           {
                               entity.EmergencyID,
                               entity.Title,
                               entity.Content,
                               entity.OrganizationID,
                               Organization = entity.Organization.OrganizationName,
                               entity.PostType,
                               entity.State,
                               entity.Creater,
                               entity.CreateDate,
                               Receivers = entity.Receivers.Select(receiver => receiver.OrganizationID).ToArray()
                           };

            return new JsonNetResult()
                       {
                           Data = new JsonResultViewModel
                                      {
                                          success = true,
                                          data = data,
                                          total = 1,
                                          message = "突发事件数据加载成功！"
                                      },
                           JsonRequestBehavior = JsonRequestBehavior.AllowGet
                       };
        }

        /// <summary>
        /// 查询突发事件数据
        /// </summary>
        /// <param name="query">查询条件模型。</param>
        /// <returns>查询结果。</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("EmergencyPoster")]
        public JsonResult SubmitSelect(JosnPagingQueryModel query)
        {
            var result = EmergencyHelper.SubmitSelect(query);

            return new JsonNetResult()
                       {
                           Data = new JsonResultViewModel
                                      {
                                          success = true,
                                          data = result.Data,
                                          total = result.Total,
                                          message = "突发事件数据加载成功！"
                                      },
                           JsonRequestBehavior = JsonRequestBehavior.AllowGet
                       };
        }

        /// <summary>
        /// 查询突发事件数据。
        /// </summary>
        /// <param name="query">查询条件模型。</param>
        /// <returns>查询结果</returns>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("EmergencyViewer|EmergencyPoster")]
        public JsonResult Select(JosnPagingQueryModel query)
        {
            var result = EmergencyHelper.Select(query);

            return new JsonNetResult()
                       {
                           Data = new JsonResultViewModel
                                      {
                                          success = true,
                                          data = result.Data,
                                          total = result.Total,
                                          message = "突发事件数据加载成功！"
                                      },
                           JsonRequestBehavior = JsonRequestBehavior.AllowGet
                       };
        }


        /// <summary>
        /// 更新突发事件
        /// </summary>
        /// <returns>执行结果。</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [ValidateInput(false)]
        [PermissionCheckAttribute("EmergencyPoster")]
        public JsonResult Update(EmergencyListRow data)
        {
            EmergencyHelper.UpdateEmergency(data);
            return Json(new JsonResultViewModel { success = true, message = "突发事件更新成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除突发事件。
        /// </summary>
        /// <returns>执行结果。</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("EmergencyPoster")]
        public JsonResult Delete(EmergencyListRow data)
        {
            EmergencyHelper.DeleteEmergency(data);
            return Json(new JsonResultViewModel { success = true, message = "突发事件删除成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 提交突发事件。
        /// </summary>
        /// <param name="emergencies">要提交的突发事件。</param>
        /// <returns>
        /// 执行结果
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("EmergencyPoster")]
        public JsonResult ExecuteSubmit(Guid[] emergencies)
        {
            EmergencyHelper.ExecuteSubmit(emergencies);
            return Json(new JsonResultViewModel { success = true, message = "突发事件提交成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除附件
        /// </summary>
        /// <returns>操作结果。</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("EmergencyPoster")]
        public JsonResult DeleteAttachment(EmergencyAttachmentModel data)
        {
            if (EmergencyHelper.DeleteAttachment(data))
                return Json(new JsonResultViewModel { success = true, message = "附件删除成功！", data = Guid.NewGuid() },
                            JsonRequestBehavior.AllowGet);

            return Json(new JsonResultViewModel { success = false, message = "附件删除失败！", data = Guid.NewGuid() },
            JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 查询附件信息
        /// </summary>
        /// <returns>查询结果。</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Attachments(Guid emergencyID)
        {
            var result = EmergencyHelper.GetEmergencyAttachment(emergencyID);

            return Json(new JsonResultViewModel
                            {
                                success = true,
                                total = result.Count,
                                message = "附件加载成功！",
                                data = result.Select(item => new EmergencyAttachmentModel
                                                                 {
                                                                     AttachmentID = item.AttachmentID,
                                                                     AttachmentName = item.AttachmentName,
                                                                     FileExtension = item.FileExtension,
                                                                     EmergencyID = item.EmergencyID
                                                                 }).ToList()
                            }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 下载附件
        /// </summary>
        /// <param name="attachmentID">附件编号。</param>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("EmergencyViewer|EmergencyPoster")]
        public ActionResult DownloadAttachment(Guid attachmentID)
        {
            var attachment = EmergencyHelper.GetAttachment(attachmentID);

            if (attachment == null)
                return Json(new JsonResultViewModel { success = false, message = "没有此突发事件附件！", data = Guid.NewGuid() }, JsonRequestBehavior.AllowGet);

            return
                File(
                    string.Concat(Server.MapPath(Utility.EmergencyFolder), Path.DirectorySeparatorChar,
                                  attachment.AttachmentID, attachment.FileExtension),
                    Utility.GetContentTypeFromFileExtension(attachment.FileExtension),
                    attachment.AttachmentName);
        }
    }
}
